<template>
  <div class="app-container towSearchHeader">
    <div class="customContainer">
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select class="w160" filterable placeholder="选择门店" v-model="formInline.store_id" style="width:300px">
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker @change="getData" :editable="false" :clearable="false" v-model="pickerDate" value-format="yyyy.MM.dd" type="daterange" align="right"
            unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" style="width:240px">
          </el-date-picker>
        </el-form-item>
        <el-select filterable placeholder="选择类型" v-model="formInline.type" style="width:90px" size="small">
          <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 进度条 -->
      <DJprogress :progressData="firProgressData" :title="firTitle" :showTags="firShowTags" :units="yAxisName"></DJprogress>
      <DJprogress :progressData="secProgressData" :title="secTitle" :color="secColor" :showTags="secShowTags" :units="yAxisName"></DJprogress>
      <DJprogress :progressData="thiProgressData" :title="thiTitle" :color="thiColor" :showTags="thiShowTags" :units="yAxisName"></DJprogress>
      <DJprogress :progressData="fouProgressData" :title="fouTitle" :color="fouColor"></DJprogress>
      <!-- 统计图 -->
      <br>
      <hr class="DJhr">
      <div style="position:relative;margin-bottom:5px">
        <p class="chartTitle" style="width:200px;margin:10px 0">消费额趋势</p>
        <span style="position:absolute;top:3px;left:100px">（机台消费）</span>
        <a v-if="showCoins==0" @click="checkCoins(0)" class="showCoins" href="javascript:;">切换为币</a>
        <a v-else @click="checkCoins(1)" class="showCoins" href="javascript:;">切换为元</a>
      </div>
      <el-row style="background:#fff;">
        <div class="legend">
          <div class="legend-item" @click="changeSelect('考核值')" :class="{'legend-fir':selectedData['考核值']}">
            <div class="legend-line"></div>
            <div class="legend-circle"></div>
            <span>考核值</span>
          </div>
          <div class="legend-item" @click="changeSelect('实际完成值')" :class="{'legend-sec':selectedData['实际完成值']}">
            <div class="legend-line"></div>
            <div class="legend-circle"></div>
            <span>实际完成值</span>
          </div>
          <div class="legend-item" @click="changeSelect('差值')" :class="{'legend-num':selectedData['差值']}">
            <div class="legend-line"></div>
            <div class="legend-circle"></div>
            <span>差值</span>
          </div>
          <el-tooltip content="请调整时间维度为7天后查看近七日对比数据" placement="bottom" effect="light" :disabled="isSenve">
            <div class="legend-item" @click="changeSelect('近七日对比')" :class="{'legend-thi':selectedData['近七日对比'],'disabled':!isSenve}">
              <div class="legend-line"></div>
              <div class="legend-circle"></div>
              <span>近七日对比</span>
            </div>
          </el-tooltip>
        </div>
        <line-chart :chart-data="lineChartData" :selectedData="selectedData" :showLegend="showLegend" :legendData="legendData" :prevSevenDate="sevenDate"
          :yAxisName="yAxisName" />
      </el-row>
      <p class="chartTitle">今日实时消费</p>
      <el-row class="table-nav">
        <el-col class="nav-item" :span="4">
          <div :class="{show:showItem==0}" @click="changeTableNav(0)">机台消费</div>
          <div :class="{show:showItem==1}" @click="changeTableNav(1)">门禁消费</div>
        </el-col>
        <el-col :span="6" :offset="14" style="text-align:right">
          <el-button type="primary" size="small" @click="jumpHistory">查看历史消费详情</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table v-show="showItem==0" highlight-current-row :data="belowList" v-loading.body="listLoading" border show-summary fit :summary-method="getSummaries"
        size="small">
        <el-table-column align="center" label="项目名称" prop="name"></el-table-column>
        <el-table-column align="center" label="游玩次数" prop="counts" sortable></el-table-column>
        <el-table-column align="center" label="收币数量" prop="push_coins" sortable :render-header="(h,obj) =>renderHeader(h,obj,'收币数量=刷卡扣币+扫码上币',showItem)">
        </el-table-column>
        <el-table-column align="center" label="收币金额" prop="push_money" sortable
          :render-header="(h,obj) => renderHeader(h,obj,'收币金额=机台收币数x当前币值+扫码支付金额',showItem)"></el-table-column>
        <el-table-column align="center" label="收币占比" sortable prop="money">
          <template slot-scope="scope">
            <span>{{scope.row.coinsRatio}}%</span>
          </template>
        </el-table-column>
      </el-table>
      <el-table v-show="showItem==1" highlight-current-row :data="belowList" v-loading.body="listLoading" border show-summary fit :summary-method="getSummaries"
        size="small">
        <el-table-column align="center" label="门禁项目" prop="name">
        </el-table-column>
        <el-table-column align="center" label="消费次数" prop="count" sortable>
          <template slot-scope="scope">
            <span style="color:#4892fb;cursor: pointer;" v-if="scope.row.name=='门票区门票'||scope.row.name=='门票区陪同票'" type="text"
              @click="showInfo(scope.row)">{{scope.row.count}}</span>
            <span v-else>{{scope.row.count}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="消费币数（星数）" prop="coins" sortable>
          <template slot-scope="scope">
            <span style="color:#4892fb;cursor: pointer;" v-if="scope.row.name=='门票区门票'||scope.row.name=='门票区陪同票'" type="text"
              @click="showInfo(scope.row)">{{scope.row.coins}}</span>
            <span v-else>{{scope.row.coins}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="消费金额" prop="money" sortable>
          <template slot-scope="scope">
            <span style="color:#4892fb;cursor: pointer;" v-if="scope.row.name=='门票区门票'||scope.row.name=='门票区陪同票'" type="text"
              @click="showInfo(scope.row)">{{scope.row.showMoney}}</span>
            <span v-else>{{scope.row.showMoney}}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹框 -->
      <el-dialog width="80%" :close-on-click-modal="false" title="消费详情" :visible.sync="detailDialog" style="margin-top:30vh">
        <el-table highlight-current-row :data="detailList" border size="small" fit>
          <el-table-column align="center" label="套餐名称" prop="name"></el-table-column>
          <el-table-column align="center" label="消费次数" prop="tickets_count"></el-table-column>
          <el-table-column align="center" label="消费币数（星数）" prop="tickets_coins"></el-table-column>
          <el-table-column align="center" label="消费金额" prop="money"></el-table-column>
          <el-table-column align="center" label="支付方式" prop="pay_type"></el-table-column>
        </el-table>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import DJprogress from './components/DJprogress';
import LineChart from './components/LineChart';
import { pickerOptionsF, pickerDateSevenDays, optionMaxTime, isSevenDays, isToday, renderHeader } from '@/utils';
import { getTodayData, chartData, getStoreList, sevenData, machineData, timesData, ticketsInfo } from '@/api/dashboard/expenseTarget';

export default {
  components: {
    DJprogress,
    LineChart
  },
  data() {
    return {
      renderHeader,
      firTitle: '今天',
      secTitle: '本月',
      thiTitle: '区间',
      fouTitle: '本月门禁',
      secColor: 'yellow',
      thiColor: 'blue',
      fouColor: 'lightBlue',
      yAxisName: '元',
      showCoins: 0,
      todayActualCoins: 0,
      todayTargetCoins: 0,
      firProgressData: {
        TargetValue: '0',
        value: '0'
      },
      secProgressData: {
        TargetValue: '0',
        value: '0'
      },
      thiProgressData: {
        TargetValue: '0',
        value: '0'
      },
      fouProgressData: {
        TargetValue: '0',
        value: '0'
      },
      firShowTags: [{ title: '新增会员', value: 0 }],
      secShowTags: [{ title: '新增会员', value: 0 }],
      thiShowTags: [{ title: '新增会员', value: 0 }],
      listLoading: false,
      detailDialog: false,
      showLegend: false,
      isSenve: true,
      showItem: 0,
      prevStoreId: 0,
      prevType: 0,
      prevShowCoins: 0,
      storeList: null,
      belowList: [],
      detailList: [],
      type_list: [
        { id: 0, name: '全部' },
        { id: 1, name: '礼品机' },
        { id: 2, name: '摊位机' },
        { id: 3, name: '彩票机' }
      ],
      selectedData: {
        考核值: true,
        实际完成值: true,
        差值: true,
        近七日对比: false
      },
      formInline: {
        store_id: '',
        start_time: '',
        end_time: '',
        type: 0,
        look_del: '0'
      },
      lineChartData: {
        dimensions: ['product', '考核值', '实际完成值', '差值', '近七日对比'],
        source: []
      },
      legendData: ['考核值', '实际完成值', '差值', '近七日对比'],
      sevenDate: [],
      pickerOptions: pickerOptionsF(),
      pickerDate: pickerDateSevenDays()
    };
  },
  activated() {
    if (this.$route.params.store_id || !this.storeList) {
      if (this.$route.params.store_id) {
        this.pickerDate = pickerDateSevenDays(-7, -1);
      }
      this.getData();
      this.getStore();
    }
  },
  methods: {
    handleSetLineChartData(type) {
      this.lineChartData = lineChartData[type];
    },
    changeSelect(key) {
      if (key === '近七日对比' && this.isSenve == false) return;
      if (this.selectedData[key]) this.selectedData[key] = false;
      else this.selectedData[key] = true;
    },
    getData() {
      optionMaxTime(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.start_time = this.pickerDate ? this.pickerDate[0] : '';
        this.formInline.end_time = this.pickerDate ? this.pickerDate[1] : '';
        if (isSevenDays(this.pickerDate)) {
          this.isSenve = true;
        } else {
          this.isSenve = false;
        }
      });
    },
    //切换币、元
    checkCoins(i) {
      if (i == 0) {
        this.showCoins = 1;
        this.yAxisName = '币';
        this.fetchData();
      } else {
        this.showCoins = 0;
        this.yAxisName = '元';
        this.fetchData();
      }
    },
    //切换展示类型
    changeTableNav(i) {
      this.showItem = i;
      if (i == 0) {
        this.getMachineData();
      } else {
        this.getTimesData();
      }
    },
    searchClick() {
      if (this.prevStoreId == this.formInline.store_id) {
        if (this.prevType != this.formInline.type || this.prevShowCoins != this.showCoins) {
          this.fetchData();
        } else {
          this.getLineData();
        }
      } else {
        this.showItem = 0;
        this.fetchData();
        this.getMachineData();
      }
    },
    // 门店列表获取
    getStore() {
      this.listLoading = true;
      getStoreList({ look_del: this.formInline.look_del, category_id: 408 }).then(response => {
        this.storeList = response;
        let data = response.filter(res => res.id == this.$store.getters.optionId);
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        } else {
          if (this.storeList.length > 0) {
            this.formInline.store_id = this.storeList[0].id;
          }
        }

        if (this.$route.params.store_id) {
          this.formInline.store_id = this.$route.params.store_id;
        }
        this.fetchData();
        this.getMachineData();
      });
    },
    fetchData() {
      getTodayData({ store_id: this.formInline.store_id, type: this.formInline.type, coin_type: this.showCoins }).then(res => {
        if (res.code == 1) {
          //今日数据
          this.firProgressData.TargetValue = (res.message.today_target_turnover / 1).toFixed(2);
          this.firProgressData.value = (res.message.today_actual_turnover / 1).toFixed(2);
          this.firShowTags[0].value = res.message.today_count / 1;
          this.todayActualCoins = res.message.today_actual_turnover / 1;
          this.todayTargetCoins = res.message.today_target_turnover / 1;
          if (this.showCoins == 1) {
            this.firProgressData.TargetValue /= 1;
            this.firProgressData.value /= 1;
          }
          //本月数
          this.secProgressData.TargetValue = (res.message.mouth_target_turnover / 1).toFixed(2);
          this.secProgressData.value = res.message.mouth_actual_turnover.toFixed(2);
          this.secShowTags[0].value = res.message.mouth_count / 1;
          if (this.showCoins == 1) {
            this.secProgressData.TargetValue /= 1;
            this.secProgressData.value /= 1;
          }
          //本月门禁
          this.fouProgressData.TargetValue = (res.message.mouth_entrance_target_turnover / 100).toFixed(2);
          this.fouProgressData.value = (res.message.mouth_entrance_actual_turnover / 1).toFixed(2);
          if (
            this.prevStoreId == 0 ||
            this.prevStoreId != this.formInline.store_id ||
            this.prevType != this.formInline.type ||
            this.prevShowCoins != this.showCoins
          ) {
            this.getLineData();
          }
        }
        this.prevStoreId = this.formInline.store_id;
      });
    },
    //获取当前时间段和折线图数据
    getLineData() {
      chartData({
        store_id: this.formInline.store_id,
        start_time: this.pickerDate[0].replace(/\./g, '-'),
        end_time: this.pickerDate[1].replace(/\./g, '-'),
        coin_type: this.showCoins,
        type: this.formInline.type
      })
        .then(res => {
          this.prevType = this.formInline.type;
          this.prevShowCoins = this.showCoins;
          let currentDates = new Date(this.pickerDate[1].replace(/\./g, '-')) - new Date(this.pickerDate[0].replace(/\./g, '-'));
          currentDates /= 1000 * 60 * 60 * 24;
          if (res.code == 1) {
            this.selectedData['考核值'] = true;
            this.selectedData['实际完成值'] = true;
            this.selectedData['差值'] = true;
            this.selectedData['近七日对比'] = false;
            this.lineChartData.source = [];
            let weekday = [' 周日', ' 周一', ' 周二', ' 周三', ' 周四', ' 周五', ' 周六'];
            if (res.message.list.length == 0) {
              if (isToday(this.pickerDate[0].replace(/\./g, '-'))) {
                let weekIndex = new Date().getDay();
                this.thiProgressData.TargetValue = this.firProgressData.TargetValue;
                this.thiProgressData.value = this.firProgressData.value;
                this.lineChartData.source.unshift({
                  product: this.pickerDate[0].replace(/\./g, '-') + weekday[weekIndex],
                  考核值: this.thiProgressData.TargetValue,
                  实际完成值: this.thiProgressData.value,
                  差值: this.thiProgressData.value - this.thiProgressData.TargetValue
                });
              } else {
                this.thiProgressData.TargetValue = (res.message.filtrate_target_turnover / 1).toFixed(2);
                this.thiProgressData.value = (res.message.filtrate_actual_turnover / 1).toFixed(2);
                this.thiShowTags[0].value = res.message.filtrate_count / 1;
              }
              return;
            }
            //当前时间段数据
            this.thiProgressData.TargetValue = (res.message.filtrate_target_turnover / 1).toFixed(2);
            this.thiProgressData.value = (res.message.filtrate_actual_turnover / 1).toFixed(2);
            this.thiShowTags[0].value = res.message.filtrate_count / 1;
            let now = new Date().toLocaleDateString().split('/');
            if (now[1] / 1 < 10) now[1] = '0' + now[1];
            if (now[2] / 1 < 10) now[2] = '0' + now[2];
            now = now.join('.');
            if (now == this.pickerDate[1]) {
              if (this.showCoins == 0) {
                this.thiProgressData.TargetValue = (this.firProgressData.TargetValue / 1 + this.thiProgressData.TargetValue / 1).toFixed(2);
                this.thiProgressData.value = (this.firProgressData.value / 1 + this.thiProgressData.value / 1).toFixed(2);
              } else {
                this.thiProgressData.TargetValue = this.firProgressData.TargetValue / 1 + this.thiProgressData.TargetValue / 1;
                this.thiProgressData.value = this.firProgressData.value / 1 + this.thiProgressData.value / 1;
              }
            }
            //折线图数据
            for (let val of res.message.list) {
              let weekIndex = new Date(val.time).getDay();
              if (this.showCoins == 0) {
                this.lineChartData.source.push({
                  product: val.time + weekday[weekIndex],
                  考核值: (val.filtrate_target_turnover / 1).toFixed(2),
                  实际完成值: (val.filtrate_actual_turnover / 1).toFixed(2),
                  差值: (val.filtrate_actual_turnover / 1 - val.filtrate_target_turnover / 1).toFixed(2)
                });
              } else {
                this.lineChartData.source.push({
                  product: val.time + weekday[weekIndex],
                  考核值: val.filtrate_target_turnover / 1,
                  实际完成值: val.filtrate_actual_turnover / 1,
                  差值: val.filtrate_actual_turnover / 1 - val.filtrate_target_turnover / 1
                });
              }
            }
            if (res.message.list.length == currentDates) {
              let date = this.pickerDate[1].replace(/\./g, '-');
              let weekIndex = new Date(date).getDay();
              this.lineChartData.source.push({
                product: date + weekday[weekIndex],
                考核值: this.firProgressData.TargetValue,
                实际完成值: this.firProgressData.value,
                差值: this.firProgressData.value - this.firProgressData.TargetValue
              });
            }
            if (this.isSenve) {
              sevenData({
                store_id: this.formInline.store_id,
                start_time: this.pickerDate[0].replace(/\./g, '-'),
                end_time: this.pickerDate[1].replace(/\./g, '-'),
                coin_type: this.showCoins,
                type: this.formInline.type
              }).then(sevenRes => {
                if (sevenRes.code == 1) {
                  this.sevenDate = [];
                  for (let i in sevenRes.message) {
                    if (this.showCoins == 0) {
                      this.lineChartData.source[i]['近七日对比'] = (sevenRes.message[i].filtrate_actual_turnover / 1).toFixed(2);
                    } else {
                      this.lineChartData.source[i]['近七日对比'] = sevenRes.message[i].filtrate_actual_turnover / 1;
                    }
                    let date = sevenRes.message[i].time;
                    let weekIndex = new Date(date).getDay();
                    this.sevenDate.push(date + weekday[weekIndex]);
                  }
                }
                this.listLoading = false;
              });
            } else {
              this.listLoading = false;
            }
          }
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    //获取机台消费明细
    getMachineData() {
      this.listLoading = true;
      this.belowList = [];
      machineData({ store_id: this.formInline.store_id })
        .then(res => {
          if (res.code == 1) {
            let total = res.message.reduce((prev, item) => item.push_coins / 1 + prev, 0);
            res.message.forEach(val => {
              val.coinsRatio = total == 0 ? '0.00' : ((val.push_coins / total) * 100).toFixed(2);
              if (val.name != '') {
                this.belowList.push(val);
              }
            });
          }
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    //获取门禁类消费明细
    getTimesData() {
      this.listLoading = true;
      this.belowList = [];
      timesData({ store_id: this.formInline.store_id })
        .then(res => {
          if (res.code == 1) {
            res.message.forEach(val => {
              if (val.count || val.count == 0) {
                val.count *= 1;
              } else {
                val.count = '-';
              }
              if (val.coins || val.coins == 0) {
                val.coins *= 1;
              } else {
                val.coins = '-';
              }
              if (val.money || val.money == 0) {
                val.showMoney = (val.money / 1000000).toFixed(2);
                val.money /= 1000000;
              } else {
                val.showMoney = '-';
                val.money = 0;
              }
            });
            this.belowList = res.message;
          }
          this.listLoading = false;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 4) {
          sums[index] = '-';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          if (index === 3) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = (sums[index] * 1).toFixed(2);
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          }
        }
      });
      return sums;
    },
    showInfo(row) {
      let now = new Date().toLocaleDateString().replace(/\//g, '.');
      let type = 0;
      if (row.name == '门票区门票') type = 1;
      ticketsInfo({ store_id: this.formInline.store_id, begin_time: now, end_time: now, look_del: 0 }, type).then(res => {
        res.forEach(val => {
          val.tickets_count = val.tickets_count || '-';
          val.tickets_coins = val.tickets_coins || '-';
          val.money = type === 1 ? (val.tickets_money * 1).toFixed(2) * 1 : (val.accompany_money * 1).toFixed(2) * 1;
        });
        this.detailList = res;
        this.detailDialog = true;
      });
    },
    //跳转营收汇总表
    jumpHistory() {
      if (this.showItem == 1) this.$router.push({ name: 'report/hxd_consume_form', params: { store_id: this.prevStoreId } });
      else this.$router.push({ name: 'report/similar_machine_gain_form', params: { store_id: this.prevStoreId } });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
div.customContainer {
  overflow-y: auto;
}
.chart-wrapper {
  background: #fff;
  padding: 15px;
  margin-bottom: 32px;
}
div.table-nav {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  div.nav-item {
    display: flex;
    justify-content: space-around;
    align-items: center;
    div {
      cursor: pointer;
      height: 32px;
      line-height: 32px;
      border-bottom: 2px solid transparent;
    }
    div.show {
      border-bottom: 2px solid #4892fb;
      color: #4892fb;
    }
  }
}
div.legend {
  z-index: 100;
  position: absolute;
  top: 2%;
  right: 10%;
  display: flex;
  font-size: 10px;
  color: #ccc;
}
div.legend div.legend-item {
  cursor: pointer;
  position: relative;
  display: flex;
  margin-left: 5px;
  div.legend-line {
    width: 26px;
    height: 5px;
    margin-right: 6px;
    border-bottom: 1px solid #ccc;
  }
  div.legend-circle {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    position: absolute;
    top: -1px;
    left: 7px;
    background: #fff;
    border: 1px solid #ccc;
  }
}
div.legend div.legend-fir {
  color: #000;
  div.legend-line {
    border-color: #5e9bdf;
  }
  div.legend-circle {
    border-color: #5e9bdf;
  }
}
div.legend div.legend-num {
  color: #000;
  div.legend-line {
    border-color: #970222;
  }
  div.legend-circle {
    border-color: #970222;
  }
}
div.legend div.legend-sec {
  color: #000;
  div.legend-line {
    border-color: #fdc927;
  }
  div.legend-circle {
    border-color: #fdc927;
  }
}
div.legend div.legend-thi {
  color: #000;
  div.legend-line {
    border-color: #ff4b4b;
  }
  div.legend-circle {
    border-color: #ff4b4b;
  }
}
div.legend div.disabled {
  cursor: no-drop;
}
a.showCoins {
  color: #409eff;
  text-decoration: underline;
  margin-left: 10px;
}
</style> 